package com.xxx.meter.ui.meter.switchgear.home;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xxx.meter.R;
import com.xxx.meter.base.BaseActivity;
import com.xxx.meter.model.data.swt.SwitchEntry;
import com.xxx.meter.model.data.swt.SwitchUtil;
import com.xxx.meter.model.http.Api;
import com.xxx.meter.model.http.ApiCallback;
import com.xxx.meter.model.http.bean.MachineChildBean;
import com.xxx.meter.model.http.bean.MachineTypeBean;
import com.xxx.meter.model.http.bean.SubmitBean;
import com.xxx.meter.model.http.bean.base.BaseBean;
import com.xxx.meter.model.http.bean.base.BooleanBean;
import com.xxx.meter.model.http.bean.base.PageBean;
import com.xxx.meter.model.utils.ButtonUtil;
import com.xxx.meter.model.utils.ToastUtil;
import com.xxx.meter.ui.main.view.ViewPagerAdapter;
import com.xxx.meter.ui.submit.SubmitWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class MeterSwitchgearActivity extends BaseActivity {

    @BindView(R.id.main_title)
    TextView mTitle;
    @BindView(R.id.main_tabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.main_viewPager)
    ViewPager mViewPager;
    @BindView(R.id.not_data)
    ImageView mNotData;
    @BindView(R.id.not_net)
    ImageView mNotNet;
    @BindView(R.id.main_data)
    LinearLayout mMainData;

    private List<Fragment> mFragmentList = new ArrayList<>();
    private List<String> mTitleList = new ArrayList<>();
    private ViewPagerAdapter mAdapter;
    private List<MachineTypeBean> mTypeList = new ArrayList<>();
    private SubmitWindow mSubmitDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_switch;
    }

    @Override
    protected void initData() {
        mTitle.setText("检测开关机时间");

        mAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList, mTitleList);
        mViewPager.setAdapter(mAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.setOffscreenPageLimit(3);

        //初始化数据
        loadDeviceTypeList();
    }

    @OnClick({R.id.main_return, R.id.switch_submit, R.id.not_data, R.id.not_net})
    public void OnClick(View view) {
        if (ButtonUtil.isFastClick()) return;
        switch (view.getId()) {
            case R.id.switch_submit:
                if (SwitchUtil.isCheck()) {
                    mSubmitDialog = SubmitWindow.getInstance(MeterSwitchgearActivity.this, 1, new SubmitWindow.Callback() {
                        @Override
                        public void onResponse(List<SubmitBean> list) {
                            if (list.size() == 0) {
                                ToastUtil.showToast("请选择提交人");
                                return;
                            }
                            String submitData = SwitchUtil.getSubmitData(list.get(0).getName());
                            submitMachineData(submitData);
                        }
                    });
                    mSubmitDialog.show();
                } else {
                    ToastUtil.showToast("请先巡查机器");
                }
                break;
            case R.id.not_data:
                loadDeviceTypeList();
                break;
            case R.id.not_net:
                loadDeviceTypeList();
                break;
            case R.id.main_return:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<SwitchEntry.DataItemEntry> switchList = SwitchUtil.getMachineSwitchList();
        for (int i = 0; i < mFragmentList.size(); i++) {
            ((MeterSwitchgearFragment) mFragmentList.get(i)).refresh(switchList);
        }
    }

    /**
     * @Model 加载巡机类型列表
     */
    private void loadDeviceTypeList() {
        Api.getInstance().getDeviceTypeList()
                .flatMap(new Function<BaseBean<PageBean<MachineTypeBean>>, ObservableSource<BaseBean<List<MachineChildBean>>>>() {
                    @Override
                    public ObservableSource<BaseBean<List<MachineChildBean>>> apply(BaseBean<PageBean<MachineTypeBean>> objectBaseBean) {
                        PageBean<MachineTypeBean> listPageBean;
                        if (objectBaseBean == null || (listPageBean = objectBaseBean.getData()) == null || listPageBean.getList() == null) {
                            mNotData.setVisibility(View.GONE);
                            mNotNet.setVisibility(View.VISIBLE);
                            mMainData.setVisibility(View.GONE);
                            throw new RuntimeException("服务器异常");
                        }

                        mTypeList.clear();
                        mTypeList.addAll(listPageBean.getList());
                        return Api.getInstance().getAllDeviceList();
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiCallback<List<MachineChildBean>>(this, true) {

                    @Override
                    public void onSuccess(List<MachineChildBean> listPageBean) {
                        mTitleList.clear();
                        mFragmentList.clear();
                        for (MachineTypeBean machineBean : mTypeList) {
                            mTitleList.add(machineBean.getName());
                            mFragmentList.add(MeterSwitchgearFragment.getInstance());
                        }
                        mAdapter.notifyDataSetChanged();

                        if (listPageBean == null || listPageBean.size() == 0) {
                            mNotData.setVisibility(View.VISIBLE);
                            mNotNet.setVisibility(View.GONE);
                            mMainData.setVisibility(View.GONE);
                            return;
                        }

                        mNotData.setVisibility(View.GONE);
                        mNotNet.setVisibility(View.GONE);
                        mMainData.setVisibility(View.VISIBLE);

                        for (int i = 0; i < mFragmentList.size(); i++) {
                            MeterSwitchgearFragment fragment = (MeterSwitchgearFragment) mFragmentList.get(i);
                            List<MachineChildBean> list = new ArrayList<>();
                            for (int i1 = 0; i1 < listPageBean.size(); i1++) {
                                MachineChildBean machineChildBean = listPageBean.get(i1);
                                if (machineChildBean.getType().equals(mTypeList.get(i).getType())) {
                                    list.add(machineChildBean);
                                }
                            }
                            fragment.loadMachineData(list);
                        }

                        //全部刷新数据
                        List<SwitchEntry.DataItemEntry> switchList = SwitchUtil.getMachineSwitchList();
                        for (Fragment fragment : mFragmentList) {
                            ((MeterSwitchgearFragment) fragment).refresh(switchList);
                        }
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                        ToastUtil.showToast(errorMessage);
                    }
                });
    }

    /**
     * @Model 提交巡机数据
     */
    private void submitMachineData(String submitData) {
        Api.getInstance().submitMachineSwitch(submitData)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiCallback<BooleanBean>(this, true) {

                    @Override
                    public void onSuccess(BooleanBean bean) {
                        if (bean.isResult()) {
                            SwitchUtil.cleanMachine();
                            //全部刷新数据
                            List<SwitchEntry.DataItemEntry> switchList = SwitchUtil.getMachineSwitchList();
                            for (Fragment fragment : mFragmentList) {
                                ((MeterSwitchgearFragment) fragment).refresh(switchList);
                            }
                            if (mSubmitDialog != null) {
                                mSubmitDialog.dismiss();
                                mSubmitDialog = null;
                            }
                            ToastUtil.showToast("提交成功");
                        } else {
                            ToastUtil.showToast("服务器异常");
                        }
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                        ToastUtil.showToast(errorMessage);
                        if (mSubmitDialog != null) {
                            mSubmitDialog.dismiss();
                            mSubmitDialog = null;
                        }
                    }
                });
    }
}
